package com.koron.css2.serviceManage.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.TService;
import com.koron.css2.serviceManage.bean.TServiceDetail;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.TServiceDetailMapper;
import com.koron.css2.serviceManage.mapper.TServiceMapper;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import org.bson.types.ObjectId;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;



public class ServiceAdd implements ServerInterface {

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {

		@SuppressWarnings("rawtypes")
		MessageBean<List> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", List.class);
		try {
			TService bean = JsonUtils.objectToPojo(req.getData(), TService.class);
			TServiceMapper mapper = factory.getMapper(TServiceMapper.class);
			TServiceDetailMapper detailMapper = factory.getMapper(TServiceDetailMapper.class);
			// 查询服务标识是否被注册
			TService tService = mapper.selectByServiceCode(bean.getServiceCode());
			if (tService != null) {
				info.setCode(Constant.MESSAGE_INT_FAIL);
				info.setDescription("操作失败，已存在与服务标识： " + tService.getServiceCode() + " ，相同的数据。");
				return info;
			} else {
				
				bean.setServiceId(new ObjectId().toHexString());
				bean.setCreateName(userInfo.getUserInfo().getName());
				bean.setCreateTime(CommonUtils.getCurrentTime());
				bean.setCallCount(0);
				mapper.insert(bean);
				if (!bean.gettServiceDetails().isEmpty()) {
					for (TServiceDetail detail : bean.gettServiceDetails()) {
						detail.setDetailId(new ObjectId().toHexString());
						detail.setServiceCode(bean.getServiceCode());
						detail.setStatus(1);
						detailMapper.insertSelective(detail);
					}
				}
			}
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return info;
	}

}
